package com.fengxing.ams.web.facade;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.fengxing.ams.pub.AMSException;
import com.fengxing.ams.web.facade.intf.IOrderFacade;
import com.fengxing.ams.web.facade.mouble.order.IOrderDAO;
import com.fengxing.ams.web.facade.mouble.order.OrderVO;
import com.fengxing.ams.web.facade.mouble.sys.ISysCodeDAO;
import com.fengxing.ams.web.facade.mouble.sys.SysCodeVO;
import com.fengxing.ams.web.facade.mouble.user.IUserDAO;
import com.fengxing.ams.web.facade.mouble.user.UserVO;

@Service
@Transactional
public class OrderFacade implements IOrderFacade {

	@Autowired
	private IOrderDAO orderDAO;
	@Autowired
	private ISysCodeDAO sysCodeDAO;
	@Autowired
	private IUserDAO userDAO;

	@Transactional(readOnly=false)
	public void save(OrderVO orderVO) {
		this.orderDAO.save(orderVO);
	}

	@Override
	public OrderVO findOne(String out_trade_no) {
		return this.orderDAO.findOne(out_trade_no);
	}

	@Transactional(readOnly=false)
	public SysCodeVO paySuccess(OrderVO order) {
		//根据userid获取用户信息
		UserVO user = userDAO.findOne(order.getUserId());
		if (user == null)
			throw new AMSException("支付完成，但没有找到用户信息，请联系管理员核实！");
		//查询一个可用的激活码
		SysCodeVO sysCode = sysCodeDAO.getOneCodeForUpdate("在线支付");
		if (sysCode == null)
			throw new AMSException("支付完成，但是没有可用的激活码，请联系管理员核实！");
		//跟新sysCode信息
		sysCode.setBuyDate(new Date());
		sysCode.setBuyEmail(user.getEmail());
		sysCode.setBuyMoney(Double.valueOf(order.getPayMoney()).intValue());
		sysCode.setStatus(4);
		
		this.sysCodeDAO.save(sysCode);
		
		//更新订单信息
		order.setSysCode(sysCode.getId());
		order.setBuyerEmail(user.getEmail());
		order.setPayStatus("1");
		
		this.orderDAO.save(order);
		
		return sysCode;
		
	}

	@Override
	public List<OrderVO> queryAllOrder(Long userId) {
		return this.orderDAO.queryAllOrder(userId);
	}

}